package xyz.ddlnt.serviceusr.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import xyz.ddlnt.commonutil.constant.MqConstants;
import xyz.ddlnt.commonutil.constant.ResultConstants;
import xyz.ddlnt.commonutil.enumeration.ResultCode;
import xyz.ddlnt.commonutil.exception.GlobalException;
import xyz.ddlnt.commonutil.util.RandomUtil;
import xyz.ddlnt.model.dto.PageDTO;
import xyz.ddlnt.model.dto.PostDescriptionDTO;
import xyz.ddlnt.model.dto.SearchDTO;
import xyz.ddlnt.model.entity.ExamQuestion;
import xyz.ddlnt.model.entity.Note;
import xyz.ddlnt.model.entity.Post;
import xyz.ddlnt.model.vo.ChildNode;
import xyz.ddlnt.model.vo.PostLatestVO;
import xyz.ddlnt.model.vo.PostNodeVO;
import xyz.ddlnt.model.vo.PostVO;
import xyz.ddlnt.serviceusr.mapper.ExamQuestionMapper;
import xyz.ddlnt.serviceusr.mapper.PostMapper;
import xyz.ddlnt.serviceusr.service.NoteService;
import xyz.ddlnt.serviceusr.service.PostService;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author ZZULI_SE 210910
 * @data 2025/5/9 16:52
 */
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {
    @Resource
    private ExamQuestionMapper examQuestionMapper;
    @Resource
    private PostMapper postMapper;
    @Resource
    private NoteService noteService;
    @Resource
    private RabbitTemplate rabbitTemplate;


    @Override
    public Boolean PublishPost(PostDescriptionDTO postDescriptionDTO) {
        Note note = noteService.getNote(postDescriptionDTO.getId());
        if (note.getNoteContent() == null || note.getNoteContent().isEmpty()) {
            throw new GlobalException(ResultCode.CONTENT_IS_EMPTY);
        }
        String tags= new JSONArray().toJSONString();
        if (postDescriptionDTO.getTags() != null && !postDescriptionDTO.getTags().isEmpty()) {
            tags= postDescriptionDTO.getTags().toJSONString();
        }
        Long postId = RandomUtil.generate12DigitRandomNumber();
        LocalDateTime now = LocalDateTime.now();
        Post post = Post.builder()
                .id(postId)
                .userId(note.getUserId())
                .postTitle(postDescriptionDTO.getPostTitle())
                .tags(tags)
                .summary(postDescriptionDTO.getSummary())
                .postDirectory(note.getNoteDirectory())
                .postContent(note.getNoteContent())
                .prevNodeId(note.getPrevNodeId())
                .prevNodeType(note.getPrevNodeType())
                .childNodes(new JSONArray().toJSONString())
                .publishTime(now)
                .updateTime(now)
                .build();
        if (postMapper.insert(post) == 1) {
            rabbitTemplate.convertAndSend(MqConstants.USR_USER, MqConstants.POST_PLUS_ONE_QUEUE, note.getUserId());
            return true;
        }
        return false;
    }

    @Override
    public List<PostVO> getPostLists(PageDTO pageDTO) {
        // TODO 标签Tags暂未处理，赋值为null
        IPage<PostVO> page = new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize());
        return postMapper.getPostLists(page);
    }

    @Override
    public List<PostVO> getBloggerPublish(PageDTO pageDTO) {
        IPage<Post> page = new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize());
        List<Post> bloggerPublish = postMapper.getBloggerPublish(page, pageDTO.getId());
        return bloggerPublish.stream().map(post -> {
            PostVO postVO = new PostVO();
            BeanUtils.copyProperties(post, postVO);
            if (post.getTags() != null && !post.getTags().isEmpty()) {
                postVO.setTags(JSONArray.parseArray(post.getTags()));
                }
            return postVO;
        }).toList();
    }

    @Override
    public List<PostVO> searchPostList(SearchDTO searchDTO) {
        IPage<PostVO> page = new Page<>(searchDTO.getPage().getPageNum(), searchDTO.getPage().getPageSize());
        return postMapper.selectPostList(page, searchDTO.getSearchValue());
    }

    @Override
    public List<PostLatestVO> getPostLatestList(Long bloggerId) {
        IPage<PostVO> page = new Page<>(1, 3);
        return postMapper.selectPostLatestList(page, bloggerId);
    }

    @Override
    public PostNodeVO getPostNodeInfo(Long postId) {
        LambdaQueryWrapper<Post> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Post::getId, postId)
                .select(Post::getPostDirectory, Post::getPrevNodeId, Post::getPrevNodeType);
        Post post = postMapper.selectOne(queryWrapper);
        JSONArray postDirectory = JSONArray.parseArray(post.getPostDirectory());
        String title = null;
        if (post.getPrevNodeType() == 1) {
            // 查试题
            LambdaQueryWrapper<ExamQuestion> queryExamQuestion = new LambdaQueryWrapper<>();
            queryExamQuestion.eq(ExamQuestion::getId, post.getPrevNodeId())
                    .select(ExamQuestion::getQuestionTitle);
            ExamQuestion examQuestion = examQuestionMapper.selectOne(queryExamQuestion);
            if (examQuestion == null) {
                title = ResultConstants.QUESTION_HAS_BEEN_DELETED;
            } else {
                title = examQuestion.getQuestionTitle();
            }
        } else if (post.getPrevNodeType() == 2) {
            // 查帖子
            LambdaQueryWrapper<Post> queryPost = new LambdaQueryWrapper<>();
            queryPost.eq(Post::getId, post.getPrevNodeId())
                    .select(Post::getPostTitle);
            Post post1 = postMapper.selectOne(queryPost);
            if (post1 == null) {
                title = ResultConstants.POST_HAS_SINCE_BEEN_DELETED;
            } else {
                title = post1.getPostTitle();
            }
        }

        LambdaQueryWrapper<Post> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Post::getPrevNodeId, postId)
                .select(Post::getId, Post::getPostDirectory, Post::getUserId, Post::getPostContent, Post::getViewCount);
        List<Post> childNodes = postMapper.selectList(queryWrapper2);

        return PostNodeVO.builder()
                .title(title)
                .postDirectory(postDirectory)
                .prevNodeId(post.getPrevNodeId())
                .prevNodeType(post.getPrevNodeType())
                .childNodes(childNodes.stream().map(childNode -> ChildNode.builder()
                        .id(childNode.getId())
                        .userId(childNode.getUserId())
                        .postContent(childNode.getPostContent())
                        .viewCount(childNode.getViewCount())
                        .build()
                ).toList())
                .build();
    }

    @Override
    public PostVO getPost(Long id) {
        PostVO postVO = postMapper.getPost(id);
        if (!StringUtils.isEmpty(postVO.getTagsArray())) {
            postVO.setTags(JSONArray.parseArray(postVO.getTagsArray()));
            postVO.setTagsArray(null);
        }
        return postVO;
    }
}

